<?php
namespace Controllers;
use Config\Base as Config;
use Exception;

/**
 * @author Eugene Baranov <evgeny@baranov.ru>
 */
abstract class Base {

    /**
     * @var string
     */
    protected $defaultAction = 'index';

    /**
     * @var string
     */
    protected $defaultView = 'Article';

    /**
     * @var string
     */
    protected $view = '';

    /**
     * @var string
     */
    protected $tmpl = '';

    public function __construct() {

    }

    /**
     *
     * @param string $action
     * @param array $param
     * @throws Exception
     * @return \Views\Base
     */
    public function run($action = null, array $param = array()) {
        if (!$action) {
            $action = $this->getDefaultAction();
        }
        if (method_exists($this, $action)) {
            $data = $this->$action($param);
            $view = $this->getView();

            foreach ($data as $key => $val) {
                $view->setData($key, $val);
            }

            return $view;
        } else {
            $c = get_called_class();
            $msg = "Method <b>{$action}</b> not exist in {$c} controller.";
            \App::error(404, $msg);
        }
        return null;
    }

    /**
     * @return string
     */
    public function getDefaultAction() {
        return $this->defaultAction;
    }

    /**
     * @param string $name
     * @return \Controllers\Base
     */
    public function setView($name) {
        $this->view = $name;
        return $this;
    }

    /**
     * @return \Views\Base
     */
    private function getView() {
        $view = $this->view ? $this->view : $this->defaultView;
        $view = \Factory::getView($view);
        if ($this->tmpl) {
            $view->setTemplate($this->tmpl);
        }
        return $view;
    }

    /**
     * @param string $name
     * @return \Controllers\Base
     */
    public function setTmpl($name) {
        $this->tmpl = $name;
        return $this;
    }

    protected function jsonSuccess($data = array()) {
        echo json_encode(array('success' => true, 'data' => $data));
        exit;
    }

    protected function jsonError($message) {
        echo json_encode(array('success' => false, 'error' => $message));
        exit;
    }

    public function haveAction($a) {
        return method_exists($this, $a);
    }
}
